package com.xudm.cdg.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xudm.cdg.entity.config.MoonShotConfig;
import com.xudm.cdg.utils.HttpClientUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xudm
 */
@Service
public class MoonShotApi {
    private final HttpClientUtil httpClientUtil;
    private final MoonShotConfig moonShotConfig;

    public MoonShotApi(HttpClientUtil httpClientUtil, MoonShotConfig moonShotConfig) {
        this.httpClientUtil = httpClientUtil;
        this.moonShotConfig = moonShotConfig;
    }

    public JSONObject singleChat(String question, String prompt) {
        String url = moonShotConfig.getUrl();
        String apiKey = moonShotConfig.getApiKey();
        String model = moonShotConfig.getModel();
        float temperature = moonShotConfig.getTemperature();

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + apiKey);

        JSONArray messages = new JSONArray();
        JSONObject sysMessage = new JSONObject();
        JSONObject body = new JSONObject();
        sysMessage.put("role", "system");
        sysMessage.put("content", prompt);

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", question);

        messages.add(sysMessage);
        messages.add(userMessage);
        body.put("messages", messages);
        body.put("model", model);
        body.put("temperature", temperature);
        String result = httpClientUtil.sendPostRequest(url, body.toString(), headers);
        return JSON.parseObject(result);
    }
}
